﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace SharpSoft.WPF.Converters
{
    /// <summary>
    /// 将枚举运行时类型所包含的枚举值和它的描述转换为字典，字典的键为枚举值，值为枚举值的描述。
    /// </summary>
    public class EnumTypeToDictionaryConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Type t && t.IsEnum)
            {
                var dic = EnumAsDictionary(t);
                return dic;
            }
            else
            {
                throw new NotSupportedException("数据源必须是枚举的运行时类型。");
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private static string GetDescription(FieldInfo field)
        {
            var att = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
            return att == null ? field.Name : ((DescriptionAttribute)att).Description;
        }

        public static Dictionary<object, string> EnumAsDictionary(Type type)
        {
            if (!type.IsEnum)
            {
                throw new NotSupportedException("必须输入枚举的运行时类型。");
            }
            Dictionary<object, string> dic = new Dictionary<object, string>();
            var values = Enum.GetValues(type);
            foreach (object item in values)
            {
                var fieldName = Enum.GetName(type, item);
                dic.Add(item, GetDescription(type.GetField(fieldName)));
            }
            return dic;
        }
    }
}
